#!/bin/bash
#
#   tbn-agent script - linux version
#   authors - TBN team:
#   Mike D'Morto ( MikeDM ) <MikeDMorto@gmail.com>
#   gemozlobin <gemozlobin@gmail.com>
#
#   20.12.2009
#

. /etc/tbn/tbn-agent.cfg

# make pref
case "$proto" in
    https)
      if [[ $ignoressl == "yes" ]]
	then crt="-k";
	else crt="--cacert /etc/tbn/server.crt";
      fi
      ;;
    http)
      crt="";
      ;;
    *)
      ;;
esac

function del_lock(){
	# remove lock
	rm -rf $flock
	rett=$?
	if [[ $rett != '0' ]]
	then echo "$(date +%d.%m.%g\ %H:%M:%S) - error delete lock file $flock" >> $flog ; exit 1;
	fi
}

#="$getter $proto://$server$s_path?"

#start
echo "$(date +%d.%m.%g\ %H:%M:%S) - start tbn-agent " >> $flog ;

# test lock
if [[ -e $flock ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error locking " >> $flog ; exit 1;
else touch $flock ; ls -la $flock;
fi

#get tasks;
echo "$(date +%d.%m.%g\ %H:%M:%S) - start download task" >> $flog
$getter $crt -o $ftmp "$proto://$server$s_path?act=get&login=$login&pass=$pass&name=$name"
ret=$?;
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error download task " >> $flog ; del_lock; exit 1;
fi
echo "$(date +%d.%m.%g\ %H:%M:%S) - success download task" >> $flog


# parse ftmp
getstatus=$(sed -n "1"p $ftmp); # status
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp" >> $flog ; del_lock; exit 1;
fi
#echo "getstatus=$getstatus";

# проверяем статус, если строка содержит err значит продолжать нет смысла, записывам ошибку в лог и выходим со снятием блокировки
if [[ $getstatus == ok* ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - get task = $getstatus" >> $flog ;
else echo "$(date +%d.%m.%g\ %H:%M:%S) - error get task = $getstatus" >> $flog ; del_lock;  exit 1;
fi

idtask=$(sed -n "2"p $ftmp); # status
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp" >> $flog ; del_lock;  exit 1;
fi
#echo "idtask=$idtask";


sname=$(sed -n "3"p $ftmp); # status
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp" >> $flog ; del_lock;  exit 1;
fi
#echo "sname=$sname";

spath=$(sed -n "4"p $ftmp); # status
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp" >> $flog ; del_lock;  exit 1;
fi
#echo "spath=$spath";

#test subscribe

#get subscribe from server
ssub=$(sed -n "5"p $ftmp);
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp" >> $flog ; del_lock;  exit 1;
fi

#generate true sebscribe
tt=$(echo -n "$serverkey$name" | md5sum | cut -f 1 -d " ");

#test subscribes 
if [[ $ssub == $tt ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - server subscribe ok" >> $flog 
else echo "$(date +%d.%m.%g\ %H:%M:%S) - server subscribe fail" >> $flog ; del_lock;  exit 1;
fi

#test ignorecache

case "$ignorecache" in  
	yes)
	  # remove script if exist
	  # rm -rf $db/$sname
	  $getter $crt -o $db/$sname "$spath"
	  ret=$?
	  if [[ $ret=='0' ]]
	    then echo "$(date +%d.%m.%g\ %H:%M:%S) - success downloading $sname " >> $flog ;
	    else echo "$(date +%d.%m.%g\ %H:%M:%S) - error downloading $sname " >> $flog ; del_lock;  exit 1;
	  fi
	  ;;
	*)	
	  # проверяем локальный кеш скриптов, если назначенного нету то скачиваем.
	  #echo "$(date +%d.%m.%g\ %H:%M:%S) - find $sname in cache dir" >> $flog ;
	  if [[ $(ls -la $db | grep $sname ) ]]
	    then echo "$(date +%d.%m.%g\ %H:%M:%S) - $sname founded in cache" >> $flog ;
	    else echo "$(date +%d.%m.%g\ %H:%M:%S) - $sname not found in cache, start download" >> $flog;
		$getter $crt -o $db/$sname "$spath"
		ret=$?
		if [[ $ret=='0' ]]
		  then echo "$(date +%d.%m.%g\ %H:%M:%S) - success downloading $sname " >> $flog ;
		  else echo "$(date +%d.%m.%g\ %H:%M:%S) - error downloading $sname " >> $flog ; del_lock;  exit 1;
		fi
	fi
	;;
esac

# докладываем серверу что взялись на исполнение скрипта = 1
echo "$(date +%d.%m.%g\ %H:%M:%S) - set status onwork to $sname " >> $flog ;
$getter $crt -o $ftmp "$proto://$server$s_path?act=status&login=$login&pass=$pass&name=$name&task=$idtask&status=1"

ret=$?;
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error update status for task <$idtask> " >> $flog ; del_lock; exit 1;
fi
# проверяем что вернулось от сервера
# parse ftmp
upstatus=$(sed -n "1"p $ftmp);
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp on update status" >> $flog ; del_lock; exit 1;
fi

if [[ $upstatus == ok* ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - success update status for task <$idtask>" >> $flog;
else echo "$(date +%d.%m.%g\ %H:%M:%S) - error update status for task <$idtask> = $upstatus" >> $flog ; del_lock;  exit 1;
fi

# стартуем на исполнение наш скрипт предварительно задав права на исполнение и меняем владельца на рута
chmod 500 $db/$sname;
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error +x to $name" >> $flog ; del_lock; exit 1;
fi

#fixit - uncomment it for real using.
chown root:root $db/$sname;
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error +x to $name" >> $flog ; del_lock; exit 1;
fi

$($db/$sname &>> $dirlog/$sname.log)
rettask=$?
echo "$sname return = $rettask";

# докладываем на сервер об исполнеии скрипта
if [[ $rettask == '0' ]]
then execstat=2; #все удачно отработало
else execstat=3; #плохо отработало. подробности читать в логах
fi

echo "$(date +%d.%m.%g\ %H:%M:%S) - set return status for $sname = $execstat" >> $flog ;
$getter $crt -o $ftmp "$proto://$server$s_path?act=status&login=$login&pass=$pass&name=$name&task=$idtask&status=$execstat"

ret=$?;
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error update status for task <$idtask> " >> $flog ; del_lock; exit 1;
fi

# проверяем что вернулось от сервера
# parse ftmp
upstatus=$(sed -n "1"p $ftmp);
ret=$?
if [[ $ret != '0' ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - error parse $ftmp on update status" >> $flog ; del_lock; exit 1;
fi

if [[ $upstatus == ok* ]]
then echo "$(date +%d.%m.%g\ %H:%M:%S) - success update status for task <$idtask>" >> $flog;
else echo "$(date +%d.%m.%g\ %H:%M:%S) - error update status for task <$idtask> = $upstatus" >> $flog ; del_lock;  exit 1;
fi

# снимаем блокировку
del_lock;
echo "$(date +%d.%m.%g\ %H:%M:%S) - stop tbn-agent" >> $flog ;
exit 0;
